package tech.xs.common.framework.config;

import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import tech.xs.common.framework.domain.constant.HttpHeaderKey;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogHandlerInterceptorAdapter extends HandlerInterceptorAdapter {

    private static final String LOG_KEY_ACCESS_TOKEN = "accessToken";
    private static final String LOG_KEY_REQUEST_ID = "requestId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader(HttpHeaderKey.ACCESS_TOKEN);
        String requestId = request.getHeader(HttpHeaderKey.REQUEST_ID);
        MDC.put(LOG_KEY_ACCESS_TOKEN, accessToken == null ? "" : accessToken);
        MDC.put(LOG_KEY_REQUEST_ID, requestId == null ? "" : requestId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(LOG_KEY_ACCESS_TOKEN);
        MDC.remove(LOG_KEY_REQUEST_ID);
    }
}
